using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace MinhUtils.Threading
{
    class Rendezvous
    {
        //number of threads that should go together
        private const int _needed = 3;

        //numbe of threads that has been counted
        private int _count = 0;

        //gate 1: open
        private Semaphore _m1 = new Semaphore(_needed);

        //gate 2: close
        private Semaphore _m2 = new Semaphore(0);

        //gather enough and I'll let you go
        public void CountMe()
        {
            _m1.Acquire();

            lock (this)
            {
                if (++_count == _needed)
                {
                    for (int i = 0; i < _needed; i++)
                    {
                        _m2.Release();
                    }
                }
            }

            _m2.Acquire();

            lock (this)
            {
                if (--_count == 0)
                {
                    for (int i = 0; i < _needed; i++)
                    {
                        _m1.Release();
                    }
                }
            }
        }
    }
}
